<template>
  <div>
    <div v-for="item in options" :key="item.value" :class="$style['option-div']">
      <paper-option
        :name="item.name"
        :text="type === 'sort' ? optionText[item.value] : item.text"
        :value="item.value"
        :type="optionType"
        :checked="checkedValues.indexOf(item.value) >= 0"
        @change="OptionChangeValue"
      />
    </div>
  </div>
</template>

<script>
import Option from '../option/option';
export default {
  name: 'OptionGroup',
  components: {
    'paper-option': Option,
  },
  props: {
    /**
     * @option 渲染的每一个小的选项 {name:string, text:string,value:string}
     * name 每一个小选项对应的提示
     * text 每一个小选项按钮的文字
     * value 每一个小选项对应的值
     * */
    options: {
      type: Array,
      require: true,
    },
    /**
     * @type string checkbox | radio | sort
     * */
    type: {
      type: String,
      default: 'checkbox',
    },
    values: {
      type: Array,
    },
  },
  data() {
    return {
      checkedValues: this.values || [],
      isCompelete: false,
    };
  },
  computed: {
    optionType: {
      get() {
        let result = this.type;
        if (this.type === 'sort') {
          result = 'radio';
        }
        return result;
      },
    },
    optionText: {
      get() {
        let result = {};
        if (this.type === 'sort') {
          this.checkedValues.forEach((item, i) => {
            result[item] = String(i + 1);
          });
        }
        return result;
      },
    },
  },
  watch: {
    checkedValues: {
      handler(newValue) {
        const length = newValue?.length || 0;
        let result = false;
        if (this.type !== 'sort') {
          if (length) {
            result = true;
          }
        } else {
          if (length === this.options?.length) {
            result = true;
          }
        }
        this.isCompelete = result;
        this.$emit('change', newValue, result);
      },
    },
  },
  methods: {
    OptionChangeValue(isChecked, checkedValue) {
      if (isChecked) {
        if (this.type === 'radio') {
          this.checkedValues = [];
        }
        this.checkedValues.push(checkedValue);
      } else {
        const order = this.checkedValues.findIndex((item) => {
          return item === checkedValue;
        });
        if (order >= 0) {
          this.checkedValues.splice(order, 1);
        }
      }
    },
  },
};
</script>

<style lang="less" module>
.option-div {
  margin-top: 16px;
}
</style>
